import os
import cv2
import numpy as np
from PyQt5.QtWidgets import QFileDialog, QMessageBox
from datetime import datetime
from PIL import Image, ImageDraw, ImageFont


def save_results(main_window):
    """保存处理结果（分割图像和测量数据）"""
    # 检查是否有原始图像和测量结果
    if main_window.source_image is None:
        QMessageBox.warning(main_window, "警告", "没有可保存的图像")
        return

    if main_window.txtResults.toPlainText() == "":
        QMessageBox.warning(main_window, "警告", "没有测量结果可保存")
        return

    # 打开保存对话框，选择保存目录
    save_dir = QFileDialog.getExistingDirectory(main_window, "选择保存目录", "")
    if not save_dir:
        return  # 用户取消了操作

    try:
        # 创建时间戳，用于生成唯一的文件名
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")

        # 保存原始图像
        source_path = os.path.join(save_dir, f"original_image_{timestamp}.png")
        cv2.imwrite(source_path, main_window.source_image)

        # 保存分割图像（如果存在）
        segmented_path = None
        if hasattr(main_window, 'segmented_image') and main_window.segmented_image is not None:
            segmented_path = os.path.join(save_dir, f"split_image_{timestamp}.png")
            cv2.imwrite(segmented_path, main_window.segmented_image)

        # 保存目标对象图像（如果存在）
        object_path = None
        if hasattr(main_window, 'mask') and main_window.mask is not None:
            # 创建目标对象图像
            object_img = np.zeros_like(main_window.source_image)
            object_img[main_window.mask] = main_window.source_image[main_window.mask]

            object_path = os.path.join(save_dir, f"target_object_{timestamp}.png")
            cv2.imwrite(object_path, object_img)

        # 合成图像路径
        combined_path = os.path.join(save_dir, f"combined_image_{timestamp}.png")

        # 创建结果合成图像 - 使用PIL支持中文
        if hasattr(main_window, 'segmented_image') and main_window.segmented_image is not None:
            # 获取原始图像和分割图像
            source_img = main_window.source_image.copy()
            segmented_img = main_window.segmented_image.copy()

            # 获取图像尺寸
            h, w, _ = source_img.shape

            # 创建合成图像 - 原始图像在左，分割图像在右
            combined_img_cv = np.zeros((h, w * 2, 3), dtype=np.uint8)
            combined_img_cv[:, :w] = source_img
            combined_img_cv[:, w:] = segmented_img

            # 转换BGR到RGB (OpenCV到PIL)
            combined_img_rgb = cv2.cvtColor(combined_img_cv, cv2.COLOR_BGR2RGB)

            # 创建PIL图像
            pil_img = Image.fromarray(combined_img_rgb)
            draw = ImageDraw.Draw(pil_img)

            # 尝试加载字体，如果失败则使用默认字体
            try:
                # 尝试加载系统中常见的中文字体
                font_paths = [
                    "C:/Windows/Fonts/simhei.ttf",  # Windows黑体
                    "C:/Windows/Fonts/simsun.ttc",  # Windows宋体
                    "/System/Library/Fonts/PingFang.ttc",  # macOS
                    "/usr/share/fonts/truetype/wqy/wqy-microhei.ttc"  # Linux文泉驿
                ]

                font = None
                for path in font_paths:
                    if os.path.exists(path):
                        font = ImageFont.truetype(path, 24)  # 标题字体
                        small_font = ImageFont.truetype(path, 20)  # 正文字体
                        break

                if font is None:
                    # 如果没找到中文字体，使用默认字体
                    font = ImageFont.load_default()
                    small_font = ImageFont.load_default()
            except Exception:
                font = ImageFont.load_default()
                small_font = ImageFont.load_default()

            # 添加标题
            draw.text((w + 10, 10), "测量结果", fill=(255, 255, 0), font=font)

            # 添加测量结果文本
            result_text = main_window.txtResults.toPlainText()
            lines = result_text.split('\n')

            # 添加每行文本
            y_position = 50
            for line in lines:
                if line.strip():  # 跳过空行
                    draw.text((w + 10, y_position), line, fill=(255, 255, 255), font=small_font)
                    y_position += 30

            # 转换回OpenCV格式并保存
            combined_img_cv = cv2.cvtColor(np.array(pil_img), cv2.COLOR_RGB2BGR)
            cv2.imwrite(combined_path, combined_img_cv)

        # 保存测量数据到文本文件
        txt_path = os.path.join(save_dir, f"测量结果_{timestamp}.txt")
        with open(txt_path, 'w', encoding='utf-8') as f:
            f.write(main_window.txtResults.toPlainText())

            # 添加额外信息
            f.write("\n\n--- 测量信息 ---\n")
            f.write(f"测量时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")

            # 添加比例尺信息
            unit = "μm"
            if main_window.radioMM.isChecked():
                unit = "mm"
            elif main_window.radioM.isChecked():
                unit = "m"

            pixel_length = main_window.txtUnitLength.text()
            scale_value = main_window.txtUnitPixels.text()
            f.write(f"比例尺: {pixel_length} 像素 = {scale_value} {unit}\n")

        # 生成HTML报告
        html_path = os.path.join(save_dir, f"报告_{timestamp}.html")
        create_html_report(main_window, html_path, timestamp, combined_path, source_path, segmented_path, object_path)

        # 显示成功消息
        QMessageBox.information(main_window, "保存成功",
                                f"所有结果已保存到:\n{save_dir}")

        # 更新状态栏
        main_window.statusbar.showMessage(f"结果已保存到: {save_dir}")

    except Exception as e:
        QMessageBox.critical(main_window, "保存失败", f"保存结果时出错: {str(e)}")
        main_window.statusbar.showMessage("保存结果失败")


def create_html_report(main_window, html_path, timestamp, combined_path, source_path, segmented_path=None,
                       object_path=None):
    """创建一个HTML格式的测量报告，使用相对路径引用图像"""
    try:
        # 获取单位信息
        unit = "μm"
        if main_window.radioMM.isChecked():
            unit = "mm"
        elif main_window.radioM.isChecked():
            unit = "m"

        # 准备测量数据
        result_text = main_window.txtResults.toPlainText()
        result_lines = result_text.split('\n')

        # 获取图像文件名（使用相对路径）
        # 由于所有文件都在同一目录下，可以直接使用文件名
        combined_img_filename = os.path.basename(combined_path)
        source_img_filename = os.path.basename(source_path)

        # 可选的分割图像和对象图像
        segmented_img_filename = os.path.basename(segmented_path) if segmented_path else None
        object_img_filename = os.path.basename(object_path) if object_path else None

        # 创建HTML内容
        html_content = f"""
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="UTF-8">
            <title>昆虫测量报告 - {timestamp}</title>
            <style>
                body {{ font-family: Arial, sans-serif; margin: 20px; }}
                h1 {{ color: #2c3e50; }}
                .result-box {{ 
                    background-color: #f8f9fa; 
                    border: 1px solid #dee2e6; 
                    border-radius: 5px; 
                    padding: 15px; 
                    margin-bottom: 20px; 
                }}
                .result-data {{ 
                    font-family: monospace; 
                    white-space: pre-wrap; 
                    margin: 10px 0; 
                }}
                .footer {{ 
                    margin-top: 30px; 
                    font-size: 0.8em; 
                    color: #6c757d; 
                    text-align: center; 
                }}
                table {{ border-collapse: collapse; width: 100%; }}
                th, td {{ 
                    border: 1px solid #dee2e6; 
                    padding: 8px; 
                    text-align: left; 
                }}
                th {{ background-color: #e9ecef; }}
                .image-container {{
                    margin: 20px 0;
                    text-align: center;
                }}
                .image-container img {{
                    max-width: 100%;
                    border: 1px solid #dee2e6;
                    border-radius: 5px;
                }}
                .image-grid {{
                    display: flex;
                    flex-wrap: wrap;
                    justify-content: space-between;
                }}
                .image-item {{
                    flex: 0 0 48%;
                    margin-bottom: 20px;
                }}
                @media (max-width: 768px) {{
                    .image-item {{
                        flex: 0 0 100%;
                    }}
                }}
            </style>
        </head>
        <body>
            <h1>昆虫测量报告</h1>

            <div class="result-box">
                <h2>测量结果图像</h2>
                <div class="image-container">
                    <img src="{combined_img_filename}" alt="合成测量结果">
                    <p>原始图像与测量结果合成图</p>
                </div>
            </div>

            <div class="result-box">
                <h2>测量数据</h2>
                <div class="result-data">
                    <table>
                        <tr>
                            <th>测量项目</th>
                            <th>测量值</th>
                        </tr>
        """

        # 解析并添加结果行
        for line in result_lines:
            if ":" in line:
                parts = line.split(":", 1)
                item = parts[0].strip()
                value = parts[1].strip()
                html_content += f"""
                        <tr>
                            <td>{item}</td>
                            <td>{value}</td>
                        </tr>
                """

        html_content += """
                    </table>
                </div>
            </div>

            <div class="result-box">
                <h2>所有图像</h2>
                <div class="image-grid">
        """

        # 添加原始图像
        html_content += f"""
                    <div class="image-item">
                        <h3>原始图像</h3>
                        <div class="image-container">
                            <img src="{source_img_filename}" alt="原始图像">
                        </div>
                    </div>
        """

        # 添加分割图像（如果存在）
        if segmented_img_filename:
            html_content += f"""
                    <div class="image-item">
                        <h3>分割图像</h3>
                        <div class="image-container">
                            <img src="{segmented_img_filename}" alt="分割图像">
                        </div>
                    </div>
            """

        # 添加对象图像（如果存在）
        if object_img_filename:
            html_content += f"""
                    <div class="image-item">
                        <h3>目标对象</h3>
                        <div class="image-container">
                            <img src="{object_img_filename}" alt="目标对象">
                        </div>
                    </div>
            """

        html_content += """
                </div>
            </div>

            <div class="result-box">
                <h2>比例尺信息</h2>
                <p>
        """

        # 添加比例尺信息
        pixel_length = main_window.txtUnitLength.text()
        scale_value = main_window.txtUnitPixels.text()
        html_content += f"""
                    <strong>比例尺换算:</strong> {pixel_length} 像素 = {scale_value} {unit}<br>
                    <strong>单位:</strong> {unit}
                </p>
            </div>

            <div class="footer">
                <p>生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}</p>
                <p>图像测量工具 © 2025</p>
            </div>
        </body>
        </html>
        """

        # 写入HTML文件
        with open(html_path, 'w', encoding='utf-8') as f:
            f.write(html_content)

    except Exception as e:
        print(f"创建HTML报告时出错: {str(e)}")


def enable_save_button(main_window):
    """在完成测量后启用保存按钮"""
    main_window.btnSave.setEnabled(True)
    main_window.actionSave.setEnabled(True)
